package com.blog.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
/**
 * 因为Spring Data Redis 默认将存储的键值通过JDK的序列化器使用Object序列化，这样子人为的到redis中读不懂，
 * 只能将key的序列化器设置为String的序列化器
 * 将value的序列化器设置为JSON的序列化器
 */
public class RedisConfiguration {
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("开始创建redis模板类~~~~");
        // 创建RedisTemplate对象
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();

        //设置Key的序列化器，默认为 JdkSerializationRedisSerializer
        // 下面是两种获取String序列化器的方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());

        // 设置value的序列化器
        // 下面是两种获取JSON序列化器的方式
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
